package com.health.healthInvoker;


import com.google.common.collect.Lists;
import com.netflix.appinfo.InstanceInfo;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.IntStream;

@RestController
@RequestMapping("/invoker")
@Configuration   //必须要加这个注解，否则无法从注册中心抓取注册客户端实例
public class InvokerController {



    @Autowired
    private DiscoveryClient discoveryClient;


    @GetMapping("/router")
    public String router(){
        List<ServiceInstance> instanceList = getServiceInstance();
        //打印所有客户端
        Object [] array =  IntStream.range(0,instanceList.size()).mapToObj(i->  {
            ServiceInstance  instance = instanceList.get(i);
            EurekaDiscoveryClient.EurekaServiceInstance eurekaInstance = (EurekaDiscoveryClient.EurekaServiceInstance) instance;
            InstanceInfo info = eurekaInstance.getInstanceInfo();
            String str = info.getAppName() + "----" + info.getInstanceId() + "---" + info.getStatus();
            System.out.println(str );
            return str;
        }).toArray();
        return ArrayUtils.toString(array);
    }


    /**
     * 查询所有实例的客户端
     * @return  List<InstanceInfo>
     */
    private List<ServiceInstance> getServiceInstance(){
        List<String> ids = discoveryClient.getServices();
        List<ServiceInstance> list = Lists.newArrayList();
        ids.forEach(serviceId->{
            System.out.println(" serviceId : " +serviceId);
            List<ServiceInstance> instance = discoveryClient.getInstances(serviceId);
            list.addAll(instance);
        });
        return list;
    }


    //使用获取元数据方式
    @GetMapping("/router2")
    public String router2(){
        //根据服务注册实例名称查询服务实例,对应eureka.instance.hostname配置
        List<ServiceInstance> instanceList = discoveryClient.getInstances("health-invoker");
        instanceList.addAll( discoveryClient.getInstances("health-provider") );
        //打印所有客户端
        Object [] array =  IntStream.range(0,instanceList.size()).mapToObj(i->  {
            ServiceInstance  instance = instanceList.get(i);
            //所有注册服务的application.yml中定义了testValue元数据,对应eureka.instance.metadata-map
            String str = instance.getMetadata().get("testValue") ;
            System.out.println(str );
            return str;
        }).toArray();
        return ArrayUtils.toString(array);
    }


}
